package com.jhws.business.property.service;

import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.business.property.bo.*;
import com.jhws.core.dataUpdate.service.DataUpdateService;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.bo.UserCommsBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.sys.user.service.UserCommsService;
import com.jhws.util.LogHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PropertyService {

    @Resource
    BaseDao BaseDao;

    @Resource
    ITblUserDimService IUserService;

    @Resource
    UserCommsService userCommsService;

    @Resource
    DataUpdateService dataUpdateService;

    /**
     * 通过where语句查找任意条件的组织数据
     *
     * @param where 已经包含where部分
     * @return
     */
    public List<PropertyOrgnazation> findOrgByWhere(String where) {
        return BaseDao.findList("from PropertyOrgnazation where 1=1 and " + where);
    }

    /**
     * 根据Id获取组织
     *
     * @param id
     * @return
     */
    public PropertyOrgnazation getOrg(Long id) {
        return BaseDao.get(PropertyOrgnazation.class, id);
    }

    /**
     * 通过id 删除组织
     *
     * @param id
     */
    public void deleteOrg(Long id) {
        BaseDao.delete(PropertyOrgnazation.class, id);
    }

    /**
     * 通过任意条件删除组织数据
     *
     * @param where
     */
    public void deleteOrgByWhere(String where) {
        BaseDao.deleteByWhere("PropertyOrgnazation", where);
    }

    /**
     * 根据id获取员工数据
     *
     * @param id
     * @return
     */
    public PropertyStaff getStaff(Long id) {
        return BaseDao.get(PropertyStaff.class, id);
    }

    /**
     * 查询满足条件的员工列表
     *
     * @param where
     * @return
     */
    public List<PropertyStaff> findStaffByWhere(String where) {
        return BaseDao.findList("from PropertyStaff where " + where);
    }

    /**
     * 获取某个组织的某种类型的员工列表
     *
     * @param orgId     组织id
     * @param staffType 员工类型，也就是app物业端子角色
     * @return
     */
    public List<PropertyStaff> getStaffByOrg(Long orgId, Integer staffType) {
        return BaseDao.findList("select ps from PropertyStaff as ps,PropertyStaffOrg as so " +
                " where 1=1 and ps.id = so.staffId and so.orgId = '" + orgId + "' " + (staffType != null ? (" and ps.staffType = '" + staffType + "'") : ""));
    }

    /**
     * 获取某个组织的某种类型的员工列表
     *
     * @param orgIds    组织id列表
     * @param staffType 员工类型，也就是app物业端子角色
     * @return
     */
    public List<PropertyStaff> getStaffByOrgs(String orgIds, Integer staffType) {
        String[] stringArr = orgIds.split(",");
        StringBuilder builder = new StringBuilder();
        for (String orgId : stringArr) {
            builder.append("'")
                    .append(orgId)
                    .append("'")
                    .append(",");
        }
        builder.deleteCharAt(builder.length() - 1);
        return BaseDao.findList("select ps from PropertyStaff as ps,PropertyStaffOrg as so " +
                " where 1=1 and ps.id = so.staffId and so.orgId in (" + builder.toString() + ") " + (staffType != null ? (" and ps.staffType = '" + staffType + "'") : ""));
    }

    /**
     * 获取某个小区的所有物业员工, 映射到PropertyStaffQueryData对象
     *
     * @param commCode 小区编号
     * @return
     */
    public List<PropertyStaffQueryData> getOrgStaffsByCommCode(String commCode) {
        return BaseDao.findList("select new com.jhws.business.property.bo.PropertyStaffQueryData(so.id,ps.id,ps.staffName,so.orgId,ps.staffType,ps.phoneNum,ps.devBinding) " +
                "from PropertyStaff as ps,PropertyStaffOrg as so " +
                "where 1=1 and ps.commCode = '" + commCode + "' and ps.id = so.staffId");
    }

    /**
     * 获取属于某个账号却不属于任何小区的员工,一般是物业公司总部所属
     *
     * @param username
     * @return
     */
    public List<PropertyStaffQueryData> getOrgStaffsByUser(String username) {
        return BaseDao.findList("select new com.jhws.business.property.bo.PropertyStaffQueryData(so.id,ps.id,ps.staffName,so.orgId,ps.staffType,ps.phoneNum,ps.devBinding) " +
                "from PropertyStaff as ps,PropertyStaffOrg as so " +
                "where 1=1 and ps.commCode = '' and ps.owner = '" + username + "' and ps.id = so.staffId");
    }

    /**
     * 查找某个小区开通了某个APP模块权限的物业用户
     *
     * @param commCode
     * @param appPerm
     * @return
     */
    public List<PropertyStaff> getStaffByCommAppPerm(String commCode, String appPerm) {
        List<UserCommsBo> list = userCommsService.findUserCommsByWhere("where comm_code = '" + commCode + "'");
        String comms = "";
        for (int i = 0; i < list.size(); i++) {
            comms += "'" + list.get(i).getUserName() + "'" + (i == list.size() - 1 ? "" : ",");
        }
        if (StringUtils.isEmpty(comms))
            return null;

        List<Long> roles = BaseDao.findList("select new java.lang.Long(role.id) from PropertyRole as role where owner in (" + comms + ") and app_perm_ids like '%" + appPerm + ",%'");
        if (roles == null || roles.size() == 0)
            return null;

        String ids = "";
        for (int i = 0; i < roles.size(); i++)
            ids += "'" + roles.get(i) + "'" + (i == roles.size() - 1 ? "" : ",");

        return BaseDao.findList("from PropertyStaff where role in (" + ids + ")");
    }

    /**
     * 推送某小区的某个模块的相应事件给开启了该权限的物业员工
     * 该方法为异步方法
     *
     * @param commCode
     * @param module
     */
    @Async
    public void notifyStaffAppModuleEvent(String commCode, String module, Long timeStamp, String title, String content) throws Exception {
        List<PropertyStaff> list = getStaffByCommAppPerm(commCode, module);
        if (list != null) {
            for (PropertyStaff staff : list) {
                dataUpdateService.pushAndUpdate(timeStamp, module, staff.getPhoneNum(), true, true, title, content);
            }
        }
    }

    /**
     * 保存任意物业表对象
     *
     * @param obj
     * @param <T>
     */
    public <T> void save(T obj) {
        BaseDao.saveOrUpdate(obj);
    }

    /**
     * 删除员工与部门得关联关系，如果所有关联清除,则删除员工本身
     *
     * @param staffOrgId
     * @param staffId
     * @param <T>
     */
    public <T> void deleteStaffOfOrg(Long staffOrgId, Long staffId) throws Exception {
        BaseDao.delete(PropertyStaffOrg.class, staffOrgId);
        Long count = BaseDao.getCountByHql("select count(*) from PropertyStaffOrg where staffId = '" + staffId + "'");
        /* 所有组织中的员工关系被删除后，就删掉员工数据和APP角色数据 */
        if (count == 0) {
            PropertyStaff staff = getStaff(staffId);
            if (StringUtils.isNotEmpty(staff.getOwnerCode())) {
                /* 先删除可能存在的管理机绑定 */
                BaseDao.executeBySql("delete sp from tbl_owner_dim as owner,tbl_sipaccount_bindings as sp " +
                        "where owner.owner_code = '" + staff.getOwnerCode() + "' and owner.room_info_num = sp.binding and owner.owner_mob = sp.username");

            /* 再删除APP角色信息，员工信息 */
                BaseDao.executeBySql("delete owner,staff from tbl_owner_dim as owner,property_staff as staff " +
                        "where owner.owner_code = staff.owner_code and staff.id = '" + staffId + "'");
            }
            /* 假如ownerCode不存在，说明没开通APP，则直接删除员工数据 */
            else {
                BaseDao.delete(PropertyStaff.class, staffId);
            }

        }
    }

    /**
     * 获取员工与组织的绑定关系
     *
     * @param where
     * @return
     */
    public List<PropertyStaffOrg> findStaffOrgBindgByWhere(String where) {
        return BaseDao.findList("from PropertyStaffOrg where 1=1 and " + where);
    }

    /**
     * 获取APP模块列表
     *
     * @return
     */
    public Map getAppModuleList() {
        return BaseDao.queryPage("from PropertyAppModule");
    }

    /**
     * 删除某个APP模块
     *
     * @param id
     */
    public void deleteAppModuleById(String id) {
        BaseDao.delete(PropertyAppModule.class, id);
    }

    /**
     * 查询APP模块列表
     *
     * @return
     */
    public Map getAppRoleList() {
        TblUserDimBo user = IUserService.currentUser();
        return BaseDao.queryPage("from PropertyRole where owner = '" + user.getLogName() + "'");
    }

    /**
     * 获取所有APP角色
     *
     * @return
     */
    public List<PropertyRole> getAppRoleAll() {
        TblUserDimBo user = IUserService.currentUser();
        return BaseDao.findList("from PropertyRole where owner = '" + user.getLogName() + "'");
    }


    /**
     * 通过ownerCode来获取物业管理员的物业角色与权限信息
     *
     * @param ownerCode
     * @return
     */
    public Map getStaffInfoByOwnerCode(String ownerCode) {
        List<PropertyStaff> staff = findStaffByWhere("owner_code = '" + ownerCode + "'");
        if (staff == null || staff.size() == 0)
            return null;
        List<PropertyStaffOrg> staffOrgs = findStaffOrgBindgByWhere("staff_id = '" + staff.get(0).getId() + "'");
        List<Map> orgRoles = new ArrayList<>();
        for (PropertyStaffOrg staffOrg : staffOrgs) {
            PropertyOrgnazation org = getOrg(staffOrg.getOrgId());
            if (org == null)
                continue;
            Map data = new HashMap();
            data.put("id", org.getId());
            data.put("orgName", org.getOrgName());
            data.put("orgRole", staff.get(0).getStaffType());
            orgRoles.add(data);
        }


        Map retMap = new HashMap();
        retMap.put("staffName", staff.get(0).getStaffName());
        retMap.put("phoneNum", staff.get(0).getPhoneNum());
        if (staff.get(0).getRole() != null){
            PropertyRole role = getAppRole(staff.get(0).getRole());
            String[] perms = role.getAppPermIds().split(",");
            retMap.put("perms", perms);
        }
        retMap.put("subRole", orgRoles);
        return retMap;
    }

    public void deleteAppRole(Long id) {
        BaseDao.delete(PropertyRole.class, id);
    }

    public PropertyRole getAppRole(Long Id) {
        return BaseDao.get(PropertyRole.class, Id);
    }

    public List<PropertyAppModule> findAppModulesByWhere(String where) {
        return BaseDao.findList("from PropertyAppModule " + where);
    }

}
